package com.cande.loki.exercise.algorithm;

import java.util.Arrays;
import java.util.Stack;

public class BigNumAdd {
    public static void main(String[] args) {
        System.out.println(addBig0("126","16"));
    }

    public static String addBig0(String a, String b){
        StringBuilder result = new StringBuilder();
        int carry = 0;
        int i = a.length()-1, j = b.length()-1;

        while (i >= 0 || j >= 0 || carry >0 ) {
            int sum1 = (i>=0) ? a.charAt(i) - '0' : 0;
            int sum2 = (j>=0) ? b.charAt(j) - '0' : 0;

            int sum = sum1 + sum2 + carry;
            carry = sum/10;
            result.append(sum%10);
            i-- ; j --;
        }
        return result.reverse().toString();
    }

    public static String addBig(String a,String b){
        StringBuilder result = new StringBuilder();
        Stack<Integer> aStack = new Stack<>();
        Stack<Integer> bStack = new Stack<>();
        String [] arr1 = a.split("");
        String [] arr2 = b.split("");
        Arrays.stream(arr1).forEach(e->aStack.push(Integer.valueOf(e)));
        Arrays.stream(arr2).forEach(e->bStack.push(Integer.valueOf(e)));
        if (arr1.length > arr2.length) {
            int extra = 0;
            while (!aStack.isEmpty()){

                int temp1 = aStack.pop();
                int temp2 = bStack.isEmpty() ?  0 : bStack.pop() ;
                int res = temp1 + temp2 + extra;
                if (res >= 10){
                    extra = Integer.parseInt(String.valueOf(res).substring(0,1));
                    result.append(String.valueOf(res).substring(1));
                }else {
                    extra = 0;
                    result.append(res);
                }

            }
        }
        return result.reverse().toString();
    }
}
